package com.metaweb.antTasks;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.LineNumberReader;
import java.io.OutputStream;
import java.io.Writer;

public abstract class Utilities {
	static public void appendUtf8File(OutputStream os, File file) throws IOException {
        InputStream is = new FileInputStream(file);
        byte[] buffer = new byte[4096];
        try {
        	int c;
        	boolean first = true;
        	
        	while ((c = is.read(buffer)) > 0) {
        		if (first) {
        			first = false;
        			if (c >= 3 && buffer[0] == (byte) 0xEF && buffer[1] == (byte) 0xBB && buffer[2] == (byte) 0xBF) {
        				os.write(buffer, 3, c - 3);
        				os.flush();
        				continue;
        			}
        		}
        		os.write(buffer, 0, c);
        		os.flush();
        	}
        } finally {
        	is.close();
        }
	}
	
	static public void appendCSSFile(Writer writer, File file, File outputFile) throws IOException {
        writer.write("\n\n/* " + file.getName() + " */\n");
        writer.flush();
		
	    String prefix = "url(";
	    String suffix = ")";
	    
        LineNumberReader reader = new LineNumberReader(new FileReader(file));
        try {
        	String relativePrefix = getRelativePrefix(outputFile, file);
            
        	String line;
        	while ((line = reader.readLine()) != null) {
        		int start = 0;
        		while (start < line.length()) {
	        		int open = line.indexOf(prefix, start);
	        		if (open >= 0) {
	        			int close = line.indexOf(suffix, open + prefix.length());
	        			if (close >= 0) {
	        				writer.write(line.substring(start, open + prefix.length()));
	        				
	        				String url = line.substring(open + prefix.length(), close);
	        				if (url.indexOf("://") < 0 && !url.startsWith("/")) { // url is relative
	        					String newURL = relativePrefix + url;
	        					writer.write(newURL);
	        				} else {
	        					writer.write(url);
	        				}
	        				
	        				writer.write(suffix);
	        				start = close + suffix.length();
	        				continue;
	        			}
	        		}
	    			writer.write(line.substring(start));
	    			break;
        		}
        		writer.write('\n');
        	}
        } finally {
        	reader.close();
        }
	}
	
	static private String getRelativePrefix(File from, File to) {
		File fromDir = from.isDirectory() ? from : from.getParentFile();
		File toDir = to.isDirectory() ? to : to.getParentFile();
		
		String fromPath = fromDir.getAbsolutePath();
		String toPath = toDir.getAbsolutePath();
		
		if (!fromPath.endsWith(File.separator)) {
			fromPath += File.separator;
		}
		if (!toPath.endsWith(File.separator)) {
			toPath += File.separator;
		}
		
		int start = 0;
		while (start < fromPath.length() && start < toPath.length() && fromPath.charAt(start) == toPath.charAt(start)) {
			start++;
		}
		start = fromPath.lastIndexOf(File.separatorChar, start);
		
		StringBuffer sb = new StringBuffer();
		int i = start + 1;
		while (i < fromPath.length()) {
			sb.append("../");
			
			i = fromPath.indexOf(File.separator, i) + 1;
		}
		
		sb.append(toPath.substring(start + 1).replace(File.separatorChar, '/'));
		
		return sb.toString();
	}
}
